/*
 * c_ini.c
 *
 * INI配置文件解析器的实现
 *
 * Created on: 2025/08/26
 *      Author: C Developer
 */

#include "c_ini/c_ini.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/* 定义注释类型枚举 */
typedef enum {
    COMMENT_TYPE_BEFORE_SECTION,  /* 节之前的注释 */
    COMMENT_TYPE_AFTER_SECTION_HEADER, /* 节头部之后的注释 */
    COMMENT_TYPE_BEFORE_KEY,      /* 键值对之前的注释 */
    COMMENT_TYPE_AFTER_KEY        /* 键值对之后的注释 */
} comment_type_t;

/* 定义注释节点结构 */
typedef struct ini_comment_t {
    char *content;               /* 注释内容 */
    comment_type_t type;         /* 注释类型 */
    char *section_name;          /* 相关节名 */
    char *key_name;              /* 相关键名，如果有关联的键值对 */
    struct ini_comment_t *next;
} ini_comment_t;

/* 定义键值对节点结构 */
typedef struct ini_key_value_t {
    char *key;
    char *value;
    ini_comment_t *comments;     /* 与该键值对相关的注释 */
    struct ini_key_value_t *next;
} ini_key_value_t;

/* 定义节节点结构 */
typedef struct ini_section_t {
    char *name;
    ini_comment_t *header_comments;  /* 节头部之后的注释 */
    ini_key_value_t *key_values;
    struct ini_section_t *next;
} ini_section_t;

/* 定义INI解析器结构 */
struct ini_parser_t {
    ini_section_t *sections;
    ini_comment_t *pre_section_comments; /* 所有节之前的注释 */
    char *filename;              /* 原始文件名 */
};

/* 前向声明 */
int ini_load_memory(ini_parser_t *parser, const char *content, size_t size);
static void free_key_values_with_comments(struct ini_key_value_t *key_values);

/* 去除字符串首尾的空白字符 */
static char *trim_whitespace(char *str)
{
    char *end;
    
    // 去除开头空白字符
    while (isspace((unsigned char)*str)) str++;
    
    // 如果字符串全是空白字符，则返回空字符串
    if (*str == '\0')
        return str;
    
    // 去除尾部空白字符
    end = str + strlen(str) - 1;
    while (end > str && isspace((unsigned char)*end)) end--;
    
    // 添加结束符
    *(end + 1) = '\0';
    
    return str;
}

/* 检查字符串是否以指定前缀开始 */
static int starts_with(const char *str, const char *prefix)
{
    return strncmp(str, prefix, strlen(prefix)) == 0;
}

/* 创建新的INI解析器实例 */
ini_parser_t *ini_create_parser(void)
{
    ini_parser_t *parser = (ini_parser_t *)malloc(sizeof(ini_parser_t));
    if (parser == NULL) {
        return NULL;
    }
    
    parser->sections = NULL;
    parser->pre_section_comments = NULL;
    parser->filename = NULL;
    return parser;
}

/* 查找指定的节 */
static ini_section_t *find_section(ini_parser_t *parser, const char *section_name)
{
    ini_section_t *current = parser->sections;
    
    while (current != NULL) {
        if (strcmp(current->name, section_name) == 0) {
            return current;
        }
        current = current->next;
    }
    
    return NULL;
}

/* 创建新的节 */
static ini_section_t *create_section(ini_parser_t *parser, const char *section_name)
{
    ini_section_t *section = (ini_section_t *)malloc(sizeof(ini_section_t));
    if (section == NULL) {
        return NULL;
    }
    
    section->name = strdup(section_name);
    if (section->name == NULL) {
        free(section);
        return NULL;
    }
    
    section->key_values = NULL;
    section->header_comments = NULL;
    section->next = NULL;
    
    // 添加到链表尾部，保持原始顺序
    if (parser->sections == NULL) {
        parser->sections = section;
    } else {
        ini_section_t *current = parser->sections;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = section;
    }
    
    return section;
}

/* 在指定节中查找键 */
static ini_key_value_t *find_key(ini_section_t *section, const char *key_name)
{
    ini_key_value_t *current = section->key_values;
    
    while (current != NULL) {
        if (strcmp(current->key, key_name) == 0) {
            return current;
        }
        current = current->next;
    }
    
    return NULL;
}

/* 从文件加载INI配置 */
int ini_load_file(ini_parser_t *parser, const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        return INI_FILE_NOT_FOUND;
    }
    
    // 保存原始文件名
    if (parser->filename) {
        free(parser->filename);
    }
    parser->filename = strdup(filename);
    if (parser->filename == NULL) {
        fclose(file);
        return INI_MEMORY_ERROR;
    }
    
    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    // 分配内存
    char *content = (char *)malloc(size + 1);
    if (content == NULL) {
        fclose(file);
        return INI_MEMORY_ERROR;
    }
    
    // 读取文件内容
    size_t read_size = fread(content, 1, size, file);
    content[read_size] = '\0';
    
    // 解析内容
    int result = ini_load_memory(parser, content, size);
    
    // 清理
    free(content);
    fclose(file);
    
    return result;
}

/* 添加注释到链表尾部 */
static int add_comment_to_list(ini_comment_t **list, const char *content, comment_type_t type, const char *section_name, const char *key_name)
{
    ini_comment_t *new_comment = (ini_comment_t *)malloc(sizeof(ini_comment_t));
    if (new_comment == NULL) {
        return INI_MEMORY_ERROR;
    }
    
    new_comment->content = strdup(content);
    new_comment->type = type;
    new_comment->section_name = section_name ? strdup(section_name) : NULL;
    new_comment->key_name = key_name ? strdup(key_name) : NULL;
    
    if (new_comment->content == NULL || 
        (section_name && new_comment->section_name == NULL) || 
        (key_name && new_comment->key_name == NULL)) {
        free(new_comment->content);
        free(new_comment->section_name);
        free(new_comment->key_name);
        free(new_comment);
        return INI_MEMORY_ERROR;
    }
    
    // 添加到链表尾部，保持原始顺序
    new_comment->next = NULL;
    
    if (*list == NULL) {
        *list = new_comment;
    } else {
        ini_comment_t *current = *list;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new_comment;
    }
    
    return INI_OK;
}

/* 添加注释到解析器 */
static int add_comment(ini_parser_t *parser, const char *content, comment_type_t type, const char *section_name, const char *key_name)
{
    if (type == COMMENT_TYPE_BEFORE_SECTION) {
        // 添加到节之前的注释链表
        return add_comment_to_list(&parser->pre_section_comments, content, type, NULL, NULL);
    } else if (type == COMMENT_TYPE_AFTER_SECTION_HEADER && section_name != NULL) {
        // 查找节并添加到节头部注释
        ini_section_t *section = find_section(parser, section_name);
        if (section == NULL) {
            return INI_ERROR;
        }
        return add_comment_to_list(&section->header_comments, content, type, section_name, NULL);
    } else if ((type == COMMENT_TYPE_BEFORE_KEY || type == COMMENT_TYPE_AFTER_KEY) && 
               section_name != NULL && key_name != NULL) {
        // 查找节和键并添加到键注释
        ini_section_t *section = find_section(parser, section_name);
        if (section == NULL) {
            return INI_ERROR;
        }
        
        ini_key_value_t *key_val = find_key(section, key_name);
        if (key_val == NULL) {
            return INI_ERROR;
        }
        
        return add_comment_to_list(&key_val->comments, content, type, section_name, key_name);
    }
    
    return INI_ERROR;
}

/* 从内存加载INI配置 */
int ini_load_memory(ini_parser_t *parser, const char *content, size_t size)
{
    if (parser == NULL || content == NULL) {
        return INI_ERROR;
    }
    
    char *buffer = strdup(content);
    if (buffer == NULL) {
        return INI_MEMORY_ERROR;
    }
    
    char *line = buffer;
    char *next_line;
    char *current_section = NULL;
    char *last_key = NULL;
    int line_num = 0;
    
    // 用于存储临时的未归属注释
    char **pending_comments = NULL;
    int pending_count = 0;
    int pending_capacity = 0;
    
    while ((next_line = strchr(line, '\n')) != NULL) {
        *next_line = '\0';
        line_num++;
        
        // 去除行首尾空白字符
        char *trimmed_line = trim_whitespace(line);
        
        if (trimmed_line[0] == ';' || trimmed_line[0] == '#') {
            // 这是注释，先添加到临时存储
            if (pending_count >= pending_capacity) {
                int new_capacity = pending_capacity + 10;
                char **new_pending = (char **)realloc(pending_comments, new_capacity * sizeof(char *));
                if (new_pending == NULL) {
                    // 释放已分配的内存
                    for (int i = 0; i < pending_count; i++) {
                        free(pending_comments[i]);
                    }
                    free(pending_comments);
                    free(buffer);
                    free(current_section);
                    free(last_key);
                    return INI_MEMORY_ERROR;
                }
                pending_comments = new_pending;
                pending_capacity = new_capacity;
            }
            pending_comments[pending_count++] = strdup(trimmed_line);
        } else if (trimmed_line[0] == '[') {
            // 这是节开始
            char *end_bracket = strrchr(trimmed_line, ']');
            if (end_bracket == NULL) {
                // 释放已分配的内存
                for (int i = 0; i < pending_count; i++) {
                    free(pending_comments[i]);
                }
                free(pending_comments);
                free(buffer);
                free(current_section);
                free(last_key);
                return INI_INVALID_FORMAT;
            }
            
            // 提取节名
            *end_bracket = '\0';
            char *section_name = trim_whitespace(trimmed_line + 1);
            
            // 处理之前的键值对关联的注释
            if (last_key != NULL && current_section != NULL) {
                for (int i = 0; i < pending_count; i++) {
                    add_comment(parser, pending_comments[i], COMMENT_TYPE_AFTER_KEY, current_section, last_key);
                    free(pending_comments[i]);
                }
                pending_count = 0;
            }
            
            // 创建或查找节
            if (current_section != NULL) {
                free(current_section);
            }
            current_section = strdup(section_name);
            if (current_section == NULL) {
                // 释放已分配的内存
                for (int i = 0; i < pending_count; i++) {
                    free(pending_comments[i]);
                }
                free(pending_comments);
                free(buffer);
                free(last_key);
                return INI_MEMORY_ERROR;
            }
            
            ini_section_t *section = create_section(parser, current_section);
            if (section == NULL) {
                // 释放已分配的内存
                for (int i = 0; i < pending_count; i++) {
                    free(pending_comments[i]);
                }
                free(pending_comments);
                free(buffer);
                free(current_section);
                free(last_key);
                return INI_MEMORY_ERROR;
            }
            
            // 将临时注释添加为节之前的注释
            for (int i = 0; i < pending_count; i++) {
                add_comment(parser, pending_comments[i], COMMENT_TYPE_BEFORE_SECTION, NULL, NULL);
                free(pending_comments[i]);
            }
            pending_count = 0;
            
            // 重置最后一个键
            free(last_key);
            last_key = NULL;
        } else if (trimmed_line[0] != '\0') {
            // 这可能是键值对
            if (current_section != NULL) {
                char *equal_sign = strchr(trimmed_line, '=');
                if (equal_sign != NULL) {
                    *equal_sign = '\0';
                    char *key = trim_whitespace(trimmed_line);
                    char *value = trim_whitespace(equal_sign + 1);
                    
                    // 处理之前的键值对关联的注释
                    if (last_key != NULL) {
                        for (int i = 0; i < pending_count; i++) {
                            add_comment(parser, pending_comments[i], COMMENT_TYPE_AFTER_KEY, current_section, last_key);
                            free(pending_comments[i]);
                        }
                        pending_count = 0;
                    }
                    
                    // 设置键值对
                    int ret = ini_set_string(parser, current_section, key, value);
                    if (ret != INI_OK) {
                        // 释放已分配的内存
                        for (int i = 0; i < pending_count; i++) {
                            free(pending_comments[i]);
                        }
                        free(pending_comments);
                        free(buffer);
                        free(current_section);
                        free(last_key);
                        return ret;
                    }
                    
                    // 将临时注释添加为当前键之前的注释
                    for (int i = 0; i < pending_count; i++) {
                        add_comment(parser, pending_comments[i], COMMENT_TYPE_BEFORE_KEY, current_section, key);
                        free(pending_comments[i]);
                    }
                    pending_count = 0;
                    
                    // 保存最后一个键
                    free(last_key);
                    last_key = strdup(key);
                    if (last_key == NULL) {
                        // 释放已分配的内存
                        free(pending_comments);
                        free(buffer);
                        free(current_section);
                        return INI_MEMORY_ERROR;
                    }
                }
            } else {
                // 非空行但不在任何节内，且不是注释，可能是无效的配置
                // 暂时忽略
            }
        }
        
        line = next_line + 1;
    }
    
    // 处理文件末尾的注释
    if (last_key != NULL && current_section != NULL) {
        for (int i = 0; i < pending_count; i++) {
            add_comment(parser, pending_comments[i], COMMENT_TYPE_AFTER_KEY, current_section, last_key);
            free(pending_comments[i]);
        }
    } else if (current_section != NULL) {
        for (int i = 0; i < pending_count; i++) {
            add_comment(parser, pending_comments[i], COMMENT_TYPE_AFTER_SECTION_HEADER, current_section, NULL);
            free(pending_comments[i]);
        }
    } else {
        for (int i = 0; i < pending_count; i++) {
            add_comment(parser, pending_comments[i], COMMENT_TYPE_BEFORE_SECTION, NULL, NULL);
            free(pending_comments[i]);
        }
    }
    
    free(pending_comments);
    free(buffer);
    free(current_section);
    free(last_key);
    return INI_OK;
}

/* 定义注释结构体类型 */
typedef struct ini_comment_t ini_comment_t;

/* 释放注释链表 */
static void free_comments(ini_comment_t *comments);

/* 保存注释链表 */
static void save_comments(FILE *file, ini_comment_t *comments)
{
    while (comments != NULL) {
        fprintf(file, "%s\n", comments->content);
        comments = comments->next;
    }
}

/* 保存INI配置到文件 */
int ini_save_file(ini_parser_t *parser, const char *filename)
{
    if (parser == NULL || filename == NULL) {
        return INI_ERROR;
    }
    
    FILE *file = fopen(filename, "w");
    if (file == NULL) {
        return INI_INVALID_FORMAT;
    }
    
    // 保存节之前的所有注释
    save_comments(file, parser->pre_section_comments);
    
    // 遍历所有节
    ini_section_t *section = parser->sections;
    while (section != NULL) {
        // 保存节名
        fprintf(file, "[%s]\n", section->name);
        
        // 保存节头部之后的注释
        save_comments(file, section->header_comments);
        
        // 保存键值对及其相关注释
        ini_key_value_t *key_value = section->key_values;
        while (key_value != NULL) {
            // 查找并保存键之前的注释
            ini_comment_t *before_key_comments = NULL;
            ini_comment_t *after_key_comments = NULL;
            ini_comment_t *comment = key_value->comments;
            
            while (comment != NULL) {
                if (comment->type == COMMENT_TYPE_BEFORE_KEY) {
                    // 添加到键之前的注释链表
                    ini_comment_t *new_comment = (ini_comment_t *)malloc(sizeof(ini_comment_t));
                    if (new_comment != NULL) {
                        new_comment->content = strdup(comment->content);
                        new_comment->type = comment->type;
                        new_comment->section_name = NULL;
                        new_comment->key_name = NULL;
                        new_comment->next = NULL;
                        
                        if (before_key_comments == NULL) {
                            before_key_comments = new_comment;
                        } else {
                            ini_comment_t *current = before_key_comments;
                            while (current->next != NULL) {
                                current = current->next;
                            }
                            current->next = new_comment;
                        }
                    }
                } else if (comment->type == COMMENT_TYPE_AFTER_KEY) {
                    // 添加到键之后的注释链表
                    ini_comment_t *new_comment = (ini_comment_t *)malloc(sizeof(ini_comment_t));
                    if (new_comment != NULL) {
                        new_comment->content = strdup(comment->content);
                        new_comment->type = comment->type;
                        new_comment->section_name = NULL;
                        new_comment->key_name = NULL;
                        new_comment->next = NULL;
                        
                        if (after_key_comments == NULL) {
                            after_key_comments = new_comment;
                        } else {
                            ini_comment_t *current = after_key_comments;
                            while (current->next != NULL) {
                                current = current->next;
                            }
                            current->next = new_comment;
                        }
                    }
                }
                comment = comment->next;
            }
            
            // 保存键之前的注释
            save_comments(file, before_key_comments);
            
            // 保存键值对
            fprintf(file, "%s=%s\n", key_value->key, key_value->value);
            
            // 保存键之后的注释
            save_comments(file, after_key_comments);
            
            // 释放临时注释链表
            while (before_key_comments != NULL) {
                ini_comment_t *temp = before_key_comments;
                before_key_comments = before_key_comments->next;
                free(temp->content);
                free(temp);
            }
            
            while (after_key_comments != NULL) {
                ini_comment_t *temp = after_key_comments;
                after_key_comments = after_key_comments->next;
                free(temp->content);
                free(temp);
            }
            
            key_value = key_value->next;
        }
        
        // 添加节之间的空行
        if (section->next != NULL) {
            fprintf(file, "\n");
        }
        
        section = section->next;
    }
    
    fclose(file);
    return INI_OK;
}

/* 获取字符串类型的配置项 */
const char *ini_get_string(ini_parser_t *parser, const char *section, const char *key, const char *default_value)
{
    ini_section_t *sec = find_section(parser, section);
    if (sec == NULL) {
        return default_value;
    }
    
    ini_key_value_t *key_val = find_key(sec, key);
    if (key_val == NULL) {
        return default_value;
    }
    
    return key_val->value;
}

/* 获取整数类型的配置项 */
int ini_get_int(ini_parser_t *parser, const char *section, const char *key, int default_value)
{
    const char *value_str = ini_get_string(parser, section, key, NULL);
    if (value_str == NULL) {
        return default_value;
    }
    
    char *endptr;
    long value = strtol(value_str, &endptr, 10);
    
    // 检查转换是否成功
    if (endptr == value_str || *endptr != '\0') {
        return default_value;
    }
    
    return (int)value;
}

/* 获取浮点数类型的配置项 */
double ini_get_double(ini_parser_t *parser, const char *section, const char *key, double default_value)
{
    const char *value_str = ini_get_string(parser, section, key, NULL);
    if (value_str == NULL) {
        return default_value;
    }
    
    char *endptr;
    double value = strtod(value_str, &endptr);
    
    // 检查转换是否成功
    if (endptr == value_str || *endptr != '\0') {
        return default_value;
    }
    
    return value;
}

/* 获取布尔类型的配置项 */
int ini_get_boolean(ini_parser_t *parser, const char *section, const char *key, int default_value)
{
    const char *value_str = ini_get_string(parser, section, key, NULL);
    if (value_str == NULL) {
        return default_value;
    }
    
    // 将字符串转换为小写进行比较
    char lower_value[64];
    size_t len = strlen(value_str);
    if (len >= sizeof(lower_value)) {
        len = sizeof(lower_value) - 1;
    }
    
    for (size_t i = 0; i < len; i++) {
        lower_value[i] = tolower((unsigned char)value_str[i]);
    }
    lower_value[len] = '\0';
    
    // 检查常见的布尔值表示
    if (strcmp(lower_value, "true") == 0 || 
        strcmp(lower_value, "yes") == 0 || 
        strcmp(lower_value, "on") == 0 || 
        strcmp(lower_value, "1") == 0) {
        return 1;
    }
    
    if (strcmp(lower_value, "false") == 0 || 
        strcmp(lower_value, "no") == 0 || 
        strcmp(lower_value, "off") == 0 || 
        strcmp(lower_value, "0") == 0) {
        return 0;
    }
    
    // 无法识别的布尔值表示，返回默认值
    return default_value;
}

/* 设置字符串类型的配置项 */
int ini_set_string(ini_parser_t *parser, const char *section, const char *key, const char *value)
{
    // 查找或创建节
    ini_section_t *sec = find_section(parser, section);
    if (sec == NULL) {
        sec = create_section(parser, section);
        if (sec == NULL) {
            return INI_MEMORY_ERROR;
        }
    }
    
    // 查找键
    ini_key_value_t *key_val = find_key(sec, key);
    if (key_val != NULL) {
        // 更新已有键的值
        free(key_val->value);
        key_val->value = strdup(value);
        if (key_val->value == NULL) {
            return INI_MEMORY_ERROR;
        }
    } else {
        // 创建新的键值对
        key_val = (ini_key_value_t *)malloc(sizeof(ini_key_value_t));
        if (key_val == NULL) {
            return INI_MEMORY_ERROR;
        }
        
        key_val->key = strdup(key);
        key_val->value = strdup(value);
        if (key_val->key == NULL || key_val->value == NULL) {
            free(key_val->key);
            free(key_val->value);
            free(key_val);
            return INI_MEMORY_ERROR;
        }
        
        // 添加到链表尾部，保持原始顺序
        key_val->next = NULL;
        
        if (sec->key_values == NULL) {
            sec->key_values = key_val;
        } else {
            ini_key_value_t *current = sec->key_values;
            while (current->next != NULL) {
                current = current->next;
            }
            current->next = key_val;
        }
    }
    
    return INI_OK;
}

/* 设置整数类型的配置项 */
int ini_set_int(ini_parser_t *parser, const char *section, const char *key, int value)
{
    char value_str[32];
    snprintf(value_str, sizeof(value_str), "%d", value);
    return ini_set_string(parser, section, key, value_str);
}

/* 设置浮点数类型的配置项 */
int ini_set_double(ini_parser_t *parser, const char *section, const char *key, double value)
{
    char value_str[64];
    snprintf(value_str, sizeof(value_str), "%g", value);
    return ini_set_string(parser, section, key, value_str);
}

/* 设置布尔类型的配置项 */
int ini_set_boolean(ini_parser_t *parser, const char *section, const char *key, int value)
{
    return ini_set_string(parser, section, key, value ? "true" : "false");
}

/* 删除指定的配置项 */
int ini_delete_key(ini_parser_t *parser, const char *section, const char *key)
{
    ini_section_t *sec = find_section(parser, section);
    if (sec == NULL) {
        return INI_ERROR;
    }
    
    ini_key_value_t *current = sec->key_values;
    ini_key_value_t *prev = NULL;
    
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            // 找到要删除的键
            if (prev == NULL) {
                // 第一个节点
                sec->key_values = current->next;
            } else {
                // 不是第一个节点
                prev->next = current->next;
            }
            
            // 释放内存
            free_comments(current->comments);
            free(current->key);
            free(current->value);
            free(current);
            
            return INI_OK;
        }
        
        prev = current;
        current = current->next;
    }
    
    // 未找到键
    return INI_ERROR;
}

/* 删除指定的节 */
int ini_delete_section(ini_parser_t *parser, const char *section)
{
    ini_section_t *current = parser->sections;
    ini_section_t *prev = NULL;
    
    while (current != NULL) {
        if (strcmp(current->name, section) == 0) {
            // 找到要删除的节
            // 释放所有键值对
            free_key_values_with_comments(current->key_values);
            
            // 释放节头部注释
            free_comments(current->header_comments);
            
            // 从链表中移除节
            if (prev == NULL) {
                // 第一个节点
                parser->sections = current->next;
            } else {
                // 不是第一个节点
                prev->next = current->next;
            }
            
            // 释放节
            free(current->name);
            free(current);
            
            return INI_OK;
        }
        
        prev = current;
        current = current->next;
    }
    
    // 未找到节
    return INI_ERROR;
}

/* 检查指定的节是否存在 */
int ini_has_section(ini_parser_t *parser, const char *section)
{
    return find_section(parser, section) != NULL;
}

/* 检查指定的配置项是否存在 */
int ini_has_key(ini_parser_t *parser, const char *section, const char *key)
{
    ini_section_t *sec = find_section(parser, section);
    if (sec == NULL) {
        return 0;
    }
    
    return find_key(sec, key) != NULL;
}

/* 获取所有节名 */
int ini_get_all_sections(ini_parser_t *parser, char **sections, int max_count)
{
    if (sections == NULL || max_count <= 0) {
        return 0;
    }
    
    int count = 0;
    ini_section_t *current = parser->sections;
    
    while (current != NULL && count < max_count) {
        sections[count++] = current->name;
        current = current->next;
    }
    
    return count;
}

/* 获取指定节下的所有键名 */
int ini_get_all_keys(ini_parser_t *parser, const char *section, char **keys, int max_count)
{
    if (keys == NULL || max_count <= 0) {
        return 0;
    }
    
    ini_section_t *sec = find_section(parser, section);
    if (sec == NULL) {
        return 0;
    }
    
    int count = 0;
    ini_key_value_t *current = sec->key_values;
    
    while (current != NULL && count < max_count) {
        keys[count++] = current->key;
        current = current->next;
    }
    
    return count;
}

/* 释放键值对及其关联的注释 */
static void free_key_values_with_comments(struct ini_key_value_t *key_values)
{
    while (key_values != NULL) {
        struct ini_key_value_t *temp = key_values;
        key_values = key_values->next;
        free_comments(temp->comments);
        free(temp->key);
        free(temp->value);
        free(temp);
    }
}

/* 释放注释链表 */
static void free_comments(ini_comment_t *comments)
{
    while (comments != NULL) {
        ini_comment_t *temp = comments;
        comments = comments->next;
        free(temp->content);
        free(temp->section_name);
        free(temp->key_name);
        free(temp);
    }
}

/* 释放INI解析器实例 */
void ini_destroy_parser(ini_parser_t *parser)
{
    if (parser == NULL) {
        return;
    }
    
    // 释放节之前的注释
    free_comments(parser->pre_section_comments);
    
    // 释放所有节、键值对和相关注释
    struct ini_section_t *section = parser->sections;
    while (section != NULL) {
        struct ini_section_t *temp_section = section;
        section = section->next;
        
        // 释放节头部注释
        free_comments(temp_section->header_comments);
        
        // 释放键值对及其注释
        free_key_values_with_comments(temp_section->key_values);
        
        free(temp_section->name);
        free(temp_section);
    }
    
    free(parser->filename);
    free(parser);
}